Sales Hub Implementation - Complete Guide
Overview
The Sales Hub / Sales Command Center is now fully functional with dynamic data from the database. This document provides a comprehensive overview of the implementation, architecture, API endpoints, and usage instructions.
๐ฏ What's Been Implemented
โ Complete Features
- **Dynamic Dashboard Metrics**
- Total Pipeline Value
- Active Deals Count
- Key Contacts Count
- Win Rate Calculation
- Weighted Revenue Forecast
- Deals by Stage Breakdown
- **AI-Powered Lead Intelligence**
- Stalled Deal Detection (>14 days inactive)
- High-Value/Low-Probability Deal Alerts
- Inactive Deal Warnings
- Actionable Recommendations
- Risk Level Classification (Critical/Warning/Info)
- **Real-Time Activity Feed**
- Email Sent Activities
- Call Completed Activities
- Stage Change Tracking
- Deal Creation Logging
- WebSocket Real-Time Updates
- **Revenue Forecasting**
- 3-Month Forecast Widget
- Weighted Forecast Calculation
- Best/Worst Case Scenarios
- Confidence Scores
- Deal Count by Month
- **Deal Pipeline Management**
- View All Active Deals
- Deal Stage Progression
- Company and Value Display
- Source Attribution (Salesforce, HubSpot, Manual)
๐ Database Schema
Core Tables
1. `sales_leads` Table
CREATE TABLE sales_leads (
id UUID PRIMARY KEY,
tenant_id UUID NOT NULL REFERENCES tenants(id),
external_id VARCHAR(255),
email VARCHAR(255) NOT NULL,
first_name VARCHAR(255),
last_name VARCHAR(255),
company VARCHAR(255),
source VARCHAR(100),
status VARCHAR(50), -- new, qualified, disqualified, contacted, spam
is_converted BOOLEAN DEFAULT FALSE,
is_spam BOOLEAN DEFAULT FALSE,
ai_score DECIMAL(5,2),
ai_qualification_summary TEXT,
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW()
);2. `deals` Table
CREATE TABLE deals (
id UUID PRIMARY KEY,
tenant_id UUID NOT NULL REFERENCES tenants(id),
name VARCHAR(255) NOT NULL,
company VARCHAR(255),
value DECIMAL(15,2) DEFAULT 0.0,
stage VARCHAR(50) NOT NULL DEFAULT 'discovery',
probability DECIMAL(5,2) DEFAULT 50.0,
source VARCHAR(100) DEFAULT 'manual',
health_score DECIMAL(5,2),
risk_level VARCHAR(20),
expected_close_date TIMESTAMP,
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW()
);3. `sales_activities` Table
CREATE TABLE sales_activities (
id UUID PRIMARY KEY,
tenant_id UUID NOT NULL REFERENCES tenants(id),
deal_id UUID NOT NULL REFERENCES deals(id),
user_id UUID REFERENCES users(id),
type VARCHAR(50) NOT NULL, -- email, call, meeting, note, stage_change
description TEXT,
timestamp TIMESTAMP DEFAULT NOW()
);๐ API Endpoints
Frontend Routes (Next.js)
1. Dashboard Stats
GET /api/sales/dashboard/stats**Response:**
{
"total_pipeline": 125000,
"active_deals_count": 8,
"key_contacts": 142,
"win_rate": 64,
"weighted_forecast": 78000,
"deals_by_stage": {
"discovery": 2,
"qualification": 3,
"proposal": 2,
"negotiation": 1
}
}2. Sales Insights
GET /api/sales/insights**Response:**
{
"status": "success",
"count": 2,
"insights": [
{
"anomaly_id": "stalled_deal_abc123",
"severity": "warning",
"title": "Deal 'Enterprise License' stalled for 15 days",
"description": "Deal worth $85,000 hasn't moved in 15 days",
"affected_entities": ["abc123"],
"platforms": ["salesforce"],
"recommendation": "Send follow-up email or schedule call to re-engage",
"action_type": "email",
"action_payload": {"deal_id": "abc123", "action": "follow_up"}
}
]
}3. Sales Activities
GET /api/sales/activities?limit=20&offset=0**Response:**
{
"status": "success",
"activities": [
{
"id": "act_123",
"type": "email",
"description": "Sent email: 'Proposal for review'",
"deal_id": "deal_123",
"deal_name": "Enterprise License - GrowthCorp",
"deal_value": 120000,
"timestamp": "2025-03-06T10:30:00Z"
}
],
"total_count": 45
}4. Revenue Forecast
GET /api/sales/forecast?months=3**Response:**
{
"status": "success",
"forecast": [
{
"month": "March 2025",
"weighted_forecast": 42000,
"best_case": 65000,
"worst_case": 21000,
"deal_count": 3,
"confidence": 72
}
],
"summary": {
"total_weighted_forecast": 126000,
"total_best_case": 195000,
"total_worst_case": 63000,
"total_deals": 9,
"avg_confidence": 68
}
}5. Pipeline Deals
GET /api/sales/pipeline**Response:**
[
{
"deal": "Enterprise License - GrowthCorp",
"value": 120000,
"status": "negotiation",
"platform": "salesforce",
"company": "GrowthCorp"
}
]Backend Routes (FastAPI)
All frontend routes proxy to these backend endpoints:
GET /api/sales/dashboard/summary?workspace_id={id}&tenant_id={id}
GET /api/sales/insights?workspace_id={id}&tenant_id={id}
GET /api/sales/activities?workspace_id={id}&tenant_id={id}&limit=20
GET /api/sales/forecast?workspace_id={id}&tenant_id={id}&months=3
GET /api/sales/pipeline?workspace_id={id}&tenant_id={id}๐งช Testing
1. Seed Sample Data
cd backend-saas
python scripts/seed_sales_demo.pyThis creates:
- 3 sample leads
- 2 sample deals
- 2 call transcripts
- 1 demo workspace
2. Test API Endpoints
# Dashboard stats
curl https://atom-saas.fly.dev/api/sales/dashboard/stats
# Insights
curl https://atom-saas.fly.dev/api/sales/insights
# Activities
curl https://atom-saas.fly.dev/api/sales/activities?limit=10
# Forecast
curl https://atom-saas.fly.dev/api/sales/forecast?months=3
# Pipeline
curl https://atom-saas.fly.dev/api/sales/pipeline3. View Dashboard
Navigate to:
https://atom-saas.fly.dev/dashboards/sales๐ค AI Features
Lead Scoring Algorithm
The lead scoring system uses:
- **Engagement Signals** (40%)
- Email opens and clicks
- Website visits
- Form submissions
- Content downloads
- **Demographic Fit** (30%)
- Company size
- Industry alignment
- Job title relevance
- Geographic location
- **Behavioral Indicators** (20%)
- Timeline to purchase
- Budget availability
- Decision maker involvement
- Competitor usage
- **External Data** (10%)
- Company funding news
- Industry trends
- Technographic data
Deal Health Scoring
Health scores are calculated based on:
- **Last Activity**: Recent engagement boosts score
- **Stage Progression**: Moving forward increases score
- **Probability Changes**: Increasing probability improves score
- **Value vs. Stage Alignment**: Large deals in early stages get lower scores
Risk Detection
The system identifies:
- **Stalled Deals**: No activity for 14+ days
- **High-Value At Risk**: Deals >$50k with <40% probability
- **Closing Soon Inactive**: Deals closing in 7 days with no recent activity
- **Long Sales Cycle**: Deals in same stage for >30 days
๐ Lead Processing Workflow
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ LEAD INGESTION โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Sources: HubSpot, Salesforce, Web Forms, Email, CSV, API โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ NORMALIZATION ENGINE โ
โ โข Standardize field names โ
โ โข Validate email formats โ
โ โข Enrich company data โ
โ โข Deduplicate existing leads โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ AI LEAD SCORING โ
โ โข Calculate engagement score โ
โ โข Assess demographic fit โ
โ โข Generate qualification summary โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ LEAD ASSIGNMENT โ
โ โข Round-robin distribution โ
โ โข Territory-based routing โ
โ โข Skill-based assignment โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ PIPELINE STAGING โ
โ Lead โ Qualified โ Proposal โ Negotiation โ Closed โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ๐ Scaling Strategy
1. Database Optimization
**Indexing Strategy:**
-- Add these indexes for performance
CREATE INDEX idx_leads_tenant_status ON sales_leads(tenant_id, status);
CREATE INDEX idx_deals_tenant_stage ON deals(tenant_id, stage);
CREATE INDEX idx_activities_tenant_timestamp ON sales_activities(tenant_id, timestamp DESC);
CREATE INDEX idx_deals_updated ON deals(tenant_id, updated_at DESC);**Partitioning:**
- Partition
sales_activitiesby month - Partition
dealsby quarter - Archive closed deals >1 year old
2. Caching Layer
# Redis cache keys
sales:stats:{tenant_id} # TTL: 5 minutes
sales:forecast:{tenant_id} # TTL: 15 minutes
sales:insights:{tenant_id} # TTL: 10 minutes
sales:pipeline:{tenant_id} # TTL: 2 minutes3. Background Jobs
# Scheduled tasks
@cron_schedule("*/5 * * * *") # Every 5 minutes
async def update_lead_scores():
# Recalculate AI scores for active leads
pass
@cron_schedule("0 */2 * * *") # Every 2 hours
async def detect_stalled_deals():
# Find and alert on stalled deals
pass
@cron_schedule("0 0 * * *") # Daily
async def generate_forecasts():
# Pre-calculate forecasts for all tenants
pass4. Horizontal Scaling
**Microservice Breakdown:**
- **Lead Ingestion Service**
- Handles all lead imports
- Queue-based processing (Celery/RabbitMQ)
- Rate limiting per tenant
- **AI Scoring Service**
- Dedicated GPU/CPU for ML models
- Batch processing for efficiency
- Separate database for ML features
- **Analytics Service**
- Pre-computed aggregations
- Time-series database (TimescaleDB)
- Materialized views for common queries
- **Integration Service**
- Salesforce, HubSpot connectors
- Webhook receivers
- API rate limiting
๐ Security & Multi-Tenancy
Tenant Isolation
All queries MUST filter by tenant_id:
# โ
CORRECT
deals = db.query(Deal).filter(
Deal.tenant_id == workspace_id
).all()
# โ WRONG - Cross-tenant data leak
deals = db.query(Deal).all()Rate Limiting
# Per-tenant rate limits
RATE_LIMITS = {
"free": 100, # 100 requests/hour
"solo": 500,
"team": 5000,
"enterprise": 50000
}Audit Logging
All sales actions are logged:
await audit_service.log_action(
tenant_id=tenant_id,
user_id=user_id,
action="deal.stage_change",
resource_type="deal",
resource_id=deal_id,
outcome="success",
metadata={"old_stage": "discovery", "new_stage": "proposal"}
)๐ Usage Analytics
Track these metrics:
- **Lead Sources Performance**
- **Stage Conversion Rates**
- **Sales Rep Performance**
๐จ UI Components
Key Components Located At:
- **Dashboard**:
src/components/dashboards/SalesCommandCenter.tsx - **Activity Feed**: Integrated in dashboard
- **Forecast Widget**: Integrated in dashboard
- **AI Insights Panel**: Integrated in dashboard
Color Coding
- **Critical Issues**: Red border/background (
bg-red-500/5 border-red-500/20) - **Warnings**: Orange border/background (
bg-orange-500/5 border-orange-500/20) - **Info**: Blue border/background (
bg-primary/5 border-primary/20)
๐ Next Steps
Phase 2 Enhancements (Future)
- **Deal Management Modal**
- Create new deals
- Edit existing deals
- Move deals between stages
- Assign sales reps
- **Advanced Analytics**
- Cohort analysis
- Funnel visualization
- Trend charts over time
- Comparison views
- **Automation Rules**
- Auto-assign leads
- Trigger follow-ups
- Stage-based notifications
- Custom workflows
- **Integrations**
- HubSpot sync
- Salesforce sync
- Google Sheets export
- Slack notifications
- **Collaboration**
- Deal comments
- @mentions
- File attachments
- Activity tagging
๐ Troubleshooting
Issue: "No data showing"
**Solution:**
- Check if workspace_id is correct
- Verify tenant isolation is working
- Run seed script:
python scripts/seed_sales_demo.py - Check browser console for API errors
Issue: "Insights not loading"
**Solution:**
- Ensure deals have updated_at timestamps
- Check DealStage enum values match
- Verify database has recent activity
- Check backend logs for errors
Issue: "Forecast shows 0"
**Solution:**
- Ensure deals have expected_close_date set
- Check probability values are set
- Verify deals are in active stages
- Check date range calculations
๐ Support
For issues or questions:
- Check backend logs:
fly logs -a atom-saas --tail 100 - Check database: Connect via psql to Neon
- Review audit logs in
saas_audit_logstable
---
**Last Updated:** March 6, 2025
**Version:** 1.0.0
**Status:** โ Production Ready